<template>
  <VPage class="app-container">
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <VGroup>
          <el-select class="selectClass" style="width: 130px;" v-model="form.orderRange.type" placeholder="请选择">
            <el-option v-for="item in orderOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <el-input v-model="form.orderRange.value" placeholder="头程单号" class="w-50"></el-input>
        </VGroup>
        <VGroup>
          <el-select class="selectClass" style="width: 100px;" v-model="form.personRange.type" placeholder="请选择">
            <el-option v-for="item in personOptions" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
          <select-personnel class="w-50" v-model="form.personRange.value"></select-personnel>
        </VGroup>
        <el-select class="selectClass" v-model="form.status" placeholder="状态" multiple collapse-tags>
          <el-option v-for="item in options['head.HeadGoodsOrder']?.[0].headGoodsOrderStatus" :key="item.value"
            :label="item.label" :value="item.value"></el-option>
        </el-select>
        <el-select class="selectClass" v-model="form.type" placeholder="发货类型" multiple collapse-tags>
          <el-option v-for="item in options['head.HeadGoodsOrder']?.[0].headGoodsOrderType" :key="item.value"
            :label="item.label" :value="item.value"></el-option>
        </el-select>
        <SelectLogistics class="selectClass" v-model:logistics="form.delivery_id"
          v-model:channel="form.logistics_channel_id" placeholder="物流商"></SelectLogistics>
        <VGroup>
          <el-select class="selectClass w-40" v-model="form.timeRange.type" style="max-width: 120px">
            <el-option v-for="item in timeOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <el-date-picker v-model="form.timeRange.value" type="daterange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" :default-time="defaultTime()"
            style="max-width: 300px" />
        </VGroup>
        <VGroup>
          <el-select class="selectClass w-30" v-model="form.skuRange.type" placeholder="请选择">
            <el-option v-for="item in skuOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <el-input v-model="form.skuRange.value" placeholder="请输入" class="w-50"></el-input>
        </VGroup>
      </template>
      <template #toolbar_btns>

        <div class="w-full">
          <el-tabs v-model="activeName" class="pl-4 pr-4" @tab-change="handleChange">
            <el-tab-pane :label="item.label" :name="item.name" v-for="(item, index) in tabList"
              :key="index"></el-tab-pane>
          </el-tabs>
        </div>
        <el-button @click="handleDistribution">手动配货</el-button>
        <el-button @click="handleCancel">取消</el-button>
        <el-button @click="handleOut">出库交接</el-button>
        <el-button @click="handlePrint">交接单打印</el-button>
        <!-- <div class="w-full">
          <el-tag class="ml-2" size="large" v-for="(item, index) in  countList" :key="index">
            {{ item.status_cn }}
            <template v-if="item.num">
              ({{ item.num }})
            </template>
          </el-tag>
        </div> -->
        <div class="flex w-full">
          <div class="mr-4 flex items-center" v-for="(item, index) in countList" :key="index">
            <span :class="['total-round', 'mr-1', filterClass(item.status)]"></span><span class="text-[#666666]">{{item.status_cn}}：</span><span class="text-bold text-[#333333]">{{ item.num }}</span>
          </div>
        </div>
      </template>
    </VTable>
    <ComModal ref="ComModalRef" @query="query"></ComModal>
    <PrintModal ref="PrintModalRef"></PrintModal>
    <VLog ref="logRef" class="dialogPublic" :api="getHeadOrderLog" type="distribution" options="id"></VLog>
    <!-- <UploadBox ref="UploadBoxRef"></UploadBox> -->
    <importFile ref="importRef" type="delivery-list" :api="importHeadOrder" @query="query"></importFile>

    <div v-show="false" ref="deliveryRef"
      style="border: 1px solid #333;background-color: #fff;width: 1000px;font-size: 10px;">
      <div style="border-bottom: 1px solid #333;text-align: center;font-size: 18px;font-weight: bold; padding: 10px 0;">
        深圳市宇环国际物流有限公司(YH)</div>
      <div
        style="border-bottom: 1px solid #333;border-bottom: 1px solid #333;text-align: center;font-size: 16px;font-weight: bold; padding: 10px 0;">
        货物交接单
      </div>
      <div style="display: flex;">
        <div
          style="width: 30%; font-weight: bold; padding: 8px 10px; border-bottom: 1px solid #333; border-right: 1px solid #333;">
          发货公司：深圳市信诚网络技术有限公司</div>
        <div
          style="width: 20%;font-weight: bold; padding: 8px 10px; border-bottom: 1px solid #333; border-right: 1px solid #333;">
          客户代码：</div>
        <div
          style="width: 20%;font-weight: bold; padding: 8px 10px;border-bottom: 1px solid #333; border-right: 1px solid #333;">
          总箱数：23</div>
        <div
          style="width: 15%;font-weight: bold; padding: 8px 10px; border-bottom: 1px solid #333; border-right: 1px solid #333;">
          收货日期：</div>
        <div style="width: 15%;font-weight: bold; padding: 8px 10px;border-bottom: 1px solid #333;">2023/09/19</div>
      </div>
      <div style="display: flex;">
        <div
          style="width: 8%;font-weight: bold; padding: 8px 10px; border-bottom: 1px solid #333; border-right: 1px solid #333;">
          序号
        </div>
        <div class="tr font-bold"
          style="width: 25%;font-weight: bold; padding: 8px 10px; border-bottom: 1px solid #333; border-right: 1px solid #333;">
          走货渠道
        </div>
        <div
          style="width: 17%;font-weight: bold; padding: 8px 10px;  border-bottom: 1px solid #333; border-right: 1px solid #333;">
          单号
        </div>
        <div
          style="width: 20%;font-weight: bold; padding: 8px 10px;  border-bottom: 1px solid #333; border-right: 1px solid #333;">
          箱数
        </div>
        <div
          style="width: 15%;font-weight: bold; padding: 8px 10px;  border-bottom: 1px solid #333; border-right: 1px solid #333;">
          目的国
        </div>
        <div style="width: 15%;font-weight: bold; padding: 8px 10px;  border-bottom: 1px solid #333;">备注
        </div>
      </div>
      <div style="display: flex;">
        <div style="width: 8%;padding: 8px 10px;  border-bottom: 1px solid #333; border-right: 1px solid #333;">1</div>
        <div style="width: 25%;padding: 8px 10px;  border-bottom: 1px solid #333; border-right: 1px solid #333;">
          美国-美森正班-卡派（包税）</div>
        <div style="width: 17%;padding: 8px 10px;  border-bottom: 1px solid #333; border-right: 1px solid #333;">
          FBA16N5RBMGF</div>
        <div style="width: 20%;padding: 8px 10px;  border-bottom: 1px solid #333; border-right: 1px solid #333;">51</div>
        <div style="width: 15%;padding: 8px 10px;  border-bottom: 1px solid #333; border-right: 1px solid #333;">LAS1
        </div>
        <div style="width: 15%;padding: 8px 10px;  border-bottom: 1px solid #333;"></div>
      </div>
      <div style="display: flex;">
        <div
          style="width: 8%;font-weight: bold; padding: 8px 10px;  border-bottom: 1px solid #333; border-right: 1px solid #333;">
          提货地址
        </div>
        <div style="width: 42%;padding: 8px 10px;  border-bottom: 1px solid #333; border-right: 1px solid #333;">
          深圳市龙岗区布吉街道秀峰工业城A6栋东侧401</div>
        <div
          style="width: 10%;font-weight: bold; padding: 8px 10px;  border-bottom: 1px solid #333; border-right: 1px solid #333;">
          联系人
        </div>
        <div style="width: 15%;padding: 8px 10px;  border-bottom: 1px solid #333; border-right: 1px solid #333;">施汉杰</div>
        <div
          style="width: 10%;font-weight: bold; padding: 8px 10px;  border-bottom: 1px solid #333; border-right: 1px solid #333;">
          联系方式
        </div>
        <div style="width: 15%;padding: 8px 10px;  border-bottom: 1px solid #333;">
          13729515214</div>
      </div>
      <div style="display: flex;">
        <div
          style="width: 8%;font-weight: bold; padding: 8px 10px; border-right: 1px solid #333; display: flex; align-items: center;">
          交接人
        </div>
        <div style="width: 42%;">
          <div style="font-weight: bold; padding: 8px 10px; border-right: 1px solid #333;">司机签名：</div>
          <div style="font-weight: bold; padding: 8px 10px; border-right: 1px solid #333;">电话：</div>
        </div>
        <div style="width: 50%;">
          <div style="border-right-width: 0px;font-weight: bold; padding: 8px 10px;">
            收货公司：深圳市宇环国际物流有限公司</div>
          <div style="font-weight: bold; padding: 8px 10px;">收货人签名：</div>
        </div>
      </div>
    </div>
  </VPage>
</template>
<script setup name="HeadDelivery-list" lang="jsx">
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, toRefs } from 'vue'
import { getEnums } from '@/api/public'
import { queryHeadOrderList, getHeadOrderLog, distributionHeadOrder, cancelHeadOrder, outHeadOrder, printHeadOrder, boxConfirmHeadOrder, importHeadOrder } from './api'
import ComModal from './components/ComModal.vue'
import PrintModal from './components/PrintModal.vue'
import VLog from '@/components/VLog';
import SelectLogistics from '@/components/SelectLogistics';
import { getLodop } from '@/utils/LodopFuncs.js';
// import UploadBox from './components/UploadBox.vue';
import importFile from '@/components/importFile';


const timeOption = [
  { label: "创建时间", value: "create_time" },
  { label: "配货时间", value: "goods_time" },
  { label: "领取时间", value: "receive_time" },
  { label: "拣货完成时间", value: "pick_complete_time" },
  { label: "装箱完成时间", value: "box_complete_time" },
  { label: "出库时间", value: "out_warehouse_time" },
  { label: "取消时间", value: "cancel_time" },
  { label: "计划发货时间", value: "deliver_goods_time" },
]

const orderOptions = [
  { label: "头程配货单号", value: "head_goods_order_no" },
  { label: "备库单号", value: "backup_warehouse_order_no" },
]

const personOptions = [
  { label: "领取人", value: "receive_user_id" },
  { label: "取消人", value: "cancel_user_id" },
  { label: "创建人", value: "create_user_id" },
  { label: "出库人", value: "outstock_join_user_id" },
]

const skuOptions = [
  { label: "SKU", value: "sku" },
  { label: "FNSKU", value: "fn_sku" },
]

const activeName = ref(0)
const tabList = [
  {
    label: '仓库自发',
    name: 0
  },
  {
    label: '工厂直发',
    name: 1
  },
]

const tableRef = ref()
const tableOptins = reactive({
  rowConfig: { height: 60 },
  formConfig: {
    data: {
      type: [1],
      orderRange: { type: 'head_goods_order_no', value: [], range: false },
      personRange: { type: 'receive_user_id', value: [], range: true },
      timeRange: { type: 'create_time', value: [], range: true },
      skuRange: { type: 'sku', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', width: "40" },
    {
      type: "seq", title: '序号', width: 80
    },
    {
      field: 'backup_warehouse_order_no', title: '备库订单号', width: 190
    },
    {
      field: 'head_goods_order_no', title: '配货单号', width: 190, slots: {
        default: ({ row }) => {
          return <div class="base-text-color" onClick={() => open('view', row.id)}>{row.head_goods_order_no}</div>
        }
      }
    },
    {
      field: 'status_cn', title: '状态', width: 100
    },
    {
      field: 'shipment_id', title: 'Shipment ID', width: 120
    },
    {
      field: 'delivery_name', title: '物流商', width: 120
    },
    {
      field: 'delivery_channel_name', title: '物流渠道', width: 120
    },
    {
      field: 'out_warehouse_name', title: '发货仓', width: 120
    },
    {
      field: 'in_warehouse_name', title: '目的仓', width: 120
    },
    {
      field: 'shipping_name', title: '运输方式', width: 120
    },
    {
      field: '', title: '发货类型', width: 120
    },
    {
      field: 'create_user', title: '创建人', width: 120
    },
    {
      field: 'create_time', title: '创建时间', width: 180
    },
    {
      field: 'deliver_goods_time', title: '计划发货时间', width: 180
    },
    {
      field: 'is_print', title: '打印', width: 120
    },
    {
      field: 'receive_user', title: '领取人', width: 120
    },
    {
      field: 'receive_time', title: '领取时间', width: 180
    },
    {
      field: 'pick_complete_time', title: '拣货完成时间', width: 180
    },
    {
      field: 'box_complete_time', title: '装箱完成时间', width: 180
    },
    {
      field: 'outstock_join_user', title: '出库交接人', width: 120
    },
    {
      field: 'outstock_join_time', title: '交接时间', width: 180
    },
    {
      title: '操作', width: "280", fixed: "right", slots: {
        default: ({ row }) => {
          return <div class="table-option">
            <div>
              <el-link type="primary" underline={false} class="mr-2" onClick={() => handleImportBox(row.id)}>导入箱数据</el-link>
              <el-link type="primary" underline={false} class="mr-2" onClick={() => handleConfirm(row.id)}>装箱确认</el-link>
              <el-link type="primary" underline={false} class="mr-2" onClick={() => openPrint(row.id)}>打印操作</el-link>
              <el-link type="primary" underline={false} class="mr-2" onClick={() => viewLog(row.id)}>查看记录</el-link>
            </div>
          </div >
        }
      }
    }
  ],
  proxyConfig: {
    seq: true,
    props: {
      result: 'data.list',
      total: 'total',
    },
    ajax: {
      query: async ({ page, form }) => {
        const res = await queryHeadOrderList({ ...form, ...page })
        countList.value = res.data.count
        return new Promise(function (resolve) {
          resolve({
            data: res.data,
            total: res.total
          })
        })
      }
    }
  }
})
const query = () => {
  tableRef.value.query()
}

const handleChange = (val) => {
  tableRef.value.setForm({ type: val == 0 ? [1] : val == 1 ? [0, 2] : '' })
  query()
}

const filterClass = (status) => {
  if(status == 1 ||status == 10 || status == 11){
    return 'yellow'
  }else if(status == 3){
    return 'red'
  }
}

const data = reactive({
  options: [],
  countList: []
})
const { options, countList } = toRefs(data)

// 获取枚举类
const fetchOption = async () => {
  getEnums({
    version: "v1", "name": [
      "head.HeadGoodsOrder"
    ]
  }).then(res => {
    options.value = res.data
  })
}
provide('options', options)
fetchOption()

const PrintModalRef = ref()
const openPrint = (id) => {
  PrintModalRef.value.open(id)
}

const handleOut = () => {
  const records = getSelectRow().map(i => {
    return i.id
  })
  if (records.length > 1) {
    ElMessage.error('只能选择一行')
    return
  }
  if (records.length == 0) {
    ElMessage.error('至少选择一行')
    return
  }
  outHeadOrder({ id: records[0] })
    .then((res) => {
      query()
      ElMessage.success(res.message)
    })
}

// 打印
const deliveryRef = ref()
const handlePrint = () => {
  const records = getSelectRow().map(i => {
    return i.id
  })
  if (records.length == 0) {
    ElMessage.error('请先选择行')
    return
  }
  // if (records.length > 1) {
  //   ElMessage.error('只能选择一行')
  //   return
  // }

  const LODOP = getLodop();
  // LODOP.SET_PRINT_PAGESIZE(1, '600mm', 0, "")
  LODOP.SET_PRINT_PAGESIZE(0, 0, 0, "A4")
  const strHtml = deliveryRef.value.innerHTML
  LODOP.ADD_PRINT_HTM(10, 10, 750, 900, strHtml);
  // console.log(table)
  // ententByIdtAreanerHTML
  LODOP.PREVIEW(); // 打印预览

  // printHeadOrder({ id: records[0] })
  //   .then((res) => {
  //     query()
  //     ElMessage.success(res.message)
  //   })
}

// 取消
const handleCancel = () => {
  const records = getSelectRow().map(i => {
    return i.id
  })
  if (records.length > 1) {
    ElMessage.error('只能选择一行')
    return
  }
  if (records.length == 0) {
    ElMessage.error('请先选择行')
    return
  }
  ElMessageBox.confirm('是否取消当前勾选项?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    cancelHeadOrder({ id: records[0] })
      .then((res) => {
        query()
        ElMessage.success(res.message)
      })
  })
}
// 装箱确认
const handleConfirm = async (id) => {
  try {
    const res = await boxConfirmHeadOrder({ id })
  } catch (e) {
    throw Error(e)
  }
}
//查看日志
const logRef = ref()
const viewLog = (id) => {
  logRef.value.open(id)
}

// 导出
const handleExport = () => {
  ElMessage.error('暂未对接')
}

// 导入箱数据
const importRef = ref()
const handleImportBox = (id) => {
  importRef.value.open(id)
}

// 手动配货
const handleDistribution = async () => {
  const records = getSelectRow().map(i => {
    return i.id
  })
  if (records.length == 0) {
    ElMessage.error('至少选择一行')
    return
  }
  try {
    const res = await distributionHeadOrder({
      ids: records
    })
    query()
    ElMessage.success(res.message)
  } catch (e) {
    throw Error(e)
  }
}
//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords()
}

const ComModalRef = ref()
const open = (type, id) => {
  ComModalRef.value.open(type, id)
}

</script>
<style>
/* .tr {
  border-right-width: 1px;
  border-bottom-width: 1px;
  border-color: #333;
  padding: 8px 10px;
}

.tr:last-child {
  border-right-width: 0px;
} */
.total-round {
  display: inline-block;
  width: 6px;
  height: 6px;
  background: #3487FF;
  border-radius: 50%;
}
.red{
  background-color: red;
}
.yellow{
  background-color: #FAAD14;
}
</style>